package com.ec.mn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ec.mn.entity.HealthRecord;
import com.ec.mn.mapper.HealthRecordMapper;
import com.ec.mn.service.HealthRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 健康数据记录 Service 实现类
 */
@Service
public class HealthRecordServiceImpl extends ServiceImpl<HealthRecordMapper, HealthRecord> implements HealthRecordService {

    @Autowired
    private HealthRecordMapper healthRecordMapper;
    
    @Override
    public List<HealthRecord> getByElderlyUserId(Long elderlyUserId) {
        return healthRecordMapper.selectByElderlyUserId(elderlyUserId);
    }
    
    @Override
    public List<HealthRecord> getAbnormalRecords() {
        return healthRecordMapper.selectAbnormalRecords();
    }
    
    @Override
    public List<HealthRecord> getAbnormalRecordsByElderlyUserId(Long elderlyUserId) {
        return healthRecordMapper.selectAbnormalRecordsByElderlyUserId(elderlyUserId);
    }
    
    @Override
    public List<HealthRecord> getByRecordType(String recordType) {
        return healthRecordMapper.selectByRecordType(recordType);
    }
    
    @Override
    public List<HealthRecord> getByElderlyUserIdAndRecordType(Long elderlyUserId, String recordType) {
        return healthRecordMapper.selectByElderlyUserIdAndRecordType(elderlyUserId, recordType);
    }
    
    @Override
    public List<HealthRecord> getByTimeRange(LocalDateTime startTime, LocalDateTime endTime) {
        return healthRecordMapper.selectByTimeRange(startTime, endTime);
    }
    
    @Override
    public List<HealthRecord> getByElderlyUserIdAndTimeRange(Long elderlyUserId, LocalDateTime startTime, LocalDateTime endTime) {
        return healthRecordMapper.selectByElderlyUserIdAndTimeRange(elderlyUserId, startTime, endTime);
    }
    
    @Override
    public Long countByElderlyUserId(Long elderlyUserId) {
        return healthRecordMapper.countByElderlyUserId(elderlyUserId);
    }
    
    @Override
    public Long countAbnormalRecords() {
        return healthRecordMapper.countAbnormalRecords();
    }
    
    @Override
    public Long countAbnormalRecordsByElderlyUserId(Long elderlyUserId) {
        return healthRecordMapper.countAbnormalRecordsByElderlyUserId(elderlyUserId);
    }
    
    @Override
    public IPage<HealthRecord> getPageWithCustom(Page<HealthRecord> page) {
        return healthRecordMapper.selectPageWithCustom(page);
    }
    
    @Override
    public IPage<HealthRecord> getPageByElderlyUserId(Page<HealthRecord> page, Long elderlyUserId) {
        return healthRecordMapper.selectPageByElderlyUserId(page, elderlyUserId);
    }
    
    @Override
    public List<HealthRecord> getRecentRecords() {
        return healthRecordMapper.selectRecentRecords();
    }
    
    @Override
    public List<HealthRecord> getRecentRecordsByElderlyUserId(Long elderlyUserId) {
        return healthRecordMapper.selectRecentRecordsByElderlyUserId(elderlyUserId);
    }
    
    @Override
    public Map<String, Object> getStatistics(Long elderlyUserId) {
        Map<String, Object> statistics = new HashMap<>();
        
        // 统计总记录数
        long totalCount = elderlyUserId != null ? 
            countByElderlyUserId(elderlyUserId) : count();
        
        // 统计异常记录数
        long abnormalCount = elderlyUserId != null ? 
            countAbnormalRecordsByElderlyUserId(elderlyUserId) : countAbnormalRecords();
        
        // 统计正常记录数
        long normalCount = totalCount - abnormalCount;
        
        // 统计各类型记录数
        Map<String, Long> typeStatistics = new HashMap<>();
        List<HealthRecord> records = elderlyUserId != null ? 
            getByElderlyUserId(elderlyUserId) : list();
        
        for (HealthRecord record : records) {
            String recordType = record.getRecordType();
            typeStatistics.put(recordType, typeStatistics.getOrDefault(recordType, 0L) + 1);
        }
        
        statistics.put("totalCount", totalCount);
        statistics.put("abnormalCount", abnormalCount);
        statistics.put("normalCount", normalCount);
        statistics.put("abnormalRate", totalCount > 0 ? (double) abnormalCount / totalCount * 100 : 0);
        statistics.put("typeStatistics", typeStatistics);
        
        return statistics;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBatch(List<HealthRecord> healthRecords) {
        return saveBatch(healthRecords, 1000); // 每批1000条
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByElderlyUserId(Long elderlyUserId) {
        QueryWrapper<HealthRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("elderly_user_id", elderlyUserId);
        return remove(queryWrapper);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByRecordType(String recordType) {
        QueryWrapper<HealthRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("record_type", recordType);
        return remove(queryWrapper);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByElderlyUserIdAndRecordType(Long elderlyUserId, String recordType) {
        QueryWrapper<HealthRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("elderly_user_id", elderlyUserId);
        queryWrapper.eq("record_type", recordType);
        return remove(queryWrapper);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAbnormalStatus(Long id, Integer isAbnormal) {
        UpdateWrapper<HealthRecord> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("is_abnormal", isAbnormal);
        return update(updateWrapper);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBatchAbnormalStatus(List<Long> ids, Integer isAbnormal) {
        UpdateWrapper<HealthRecord> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", ids);
        updateWrapper.set("is_abnormal", isAbnormal);
        return update(updateWrapper);
    }
    

    /**
     * 重写更新方法，添加业务逻辑
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateById(HealthRecord healthRecord) {
        // 设置更新时间
        healthRecord.setRecordedAt(LocalDateTime.now());
        return super.updateById(healthRecord);
    }
    
    /**
     * 根据条件查询健康记录
     */
    public List<HealthRecord> getByCondition(Long elderlyUserId, String recordType, Integer isAbnormal, 
                                           LocalDateTime startTime, LocalDateTime endTime) {
        QueryWrapper<HealthRecord> queryWrapper = new QueryWrapper<>();
        
        if (elderlyUserId != null) {
            queryWrapper.eq("elderly_user_id", elderlyUserId);
        }
        if (recordType != null && !recordType.trim().isEmpty()) {
            queryWrapper.eq("record_type", recordType);
        }
        if (isAbnormal != null) {
            queryWrapper.eq("is_abnormal", isAbnormal);
        }
        if (startTime != null) {
            queryWrapper.ge("recorded_at", startTime);
        }
        if (endTime != null) {
            queryWrapper.le("recorded_at", endTime);
        }
        
        queryWrapper.orderByDesc("recorded_at");
        return list(queryWrapper);
    }
    
    /**
     * 获取健康记录的趋势数据
     */
    public Map<String, Object> getTrendData(Long elderlyUserId, String recordType, Integer days) {
        Map<String, Object> trendData = new HashMap<>();
        
        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime startTime = endTime.minusDays(days != null ? days : 7);
        
        List<HealthRecord> records = getByElderlyUserIdAndTimeRange(elderlyUserId, startTime, endTime);
        
        // 按日期分组统计
        Map<String, List<HealthRecord>> dailyRecords = new HashMap<>();
        for (HealthRecord record : records) {
            String date = record.getRecordedAt().toLocalDate().toString();
            dailyRecords.computeIfAbsent(date, k -> new ArrayList<>()).add(record);
        }
        
        trendData.put("dailyRecords", dailyRecords);
        trendData.put("totalRecords", records.size());
        trendData.put("startDate", startTime.toLocalDate());
        trendData.put("endDate", endTime.toLocalDate());
        
        return trendData;
    }
}
